package io.renren.sdapi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import io.renren.constant.RedisKeyConstant;
import io.renren.membermanage.dto.SseCommonMessageDto;
import io.renren.sdapi.dto.httprequestparam.SseMessageDto;
import io.renren.sdapi.service.SseService;
import io.renren.util.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Service
public class SseServiceImpl implements SseService {

    private static Map<String, SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();

    @Override
    public SseEmitter connect(String uuid) {
        SseEmitter sseEmitter = new SseEmitter();
        // 连接成功需要返回数据，否则会出现待处理状态
        try {
            sseEmitter.send(SseEmitter.event().comment("welcome"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 连接断开
        sseEmitter.onCompletion(() -> {
            sseEmitterMap.remove(uuid);
        });
        // 连接超时
        sseEmitter.onTimeout(() -> {
            sseEmitterMap.remove(uuid);
        });
        // 连接报错
        sseEmitter.onError((throwable) -> {
            sseEmitterMap.remove(uuid);
        });
        sseEmitterMap.put(uuid, sseEmitter);
        return sseEmitter;
    }

    /**
     * 目前仅为demo,后续需要封装具体消息体
     * @param message
     */
    @Override
    public void sendMessage(SseMessageDto message) {
        sseEmitterMap.forEach((uuid, sseEmitter) -> {
            try {
                sseEmitter.send(message, MediaType.APPLICATION_JSON);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    /**
     * 目前仅为demo,后续需要封装具体消息体
     * @param message
     */
    @Override
    public void sendMessage(SseCommonMessageDto message) {
        sseEmitterMap.forEach((uuid, sseEmitter) -> {
            try {
                sseEmitter.send(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }
}
